import globalVisionEntertainment.nba.Database;
import globalVisionEntertainment.nba.NbaScorePredictor;
import globalVisionEntertainment.nba.PlayerPairScoreGain;

import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;

public class Program
{

	public static void main(String[] args) throws ClassNotFoundException
	{
		String fileName = args[0];
		BufferedReader reader = null;
		BufferedWriter writer = null;
		int lineNumber = 0;
		String line = null;
		Connection connection = null;
		try
		{
			Class.forName("com.mysql.jdbc.Driver");
			connection = Database.getConnection();

			reader = new BufferedReader(new FileReader(fileName));

			writer = new BufferedWriter(new FileWriter("output.csv"));
			// SimpleDateFormat fileDateFormat = new SimpleDateFormat("M/d/yyyy");
			// SimpleDateFormat libDataFormat = new SimpleDateFormat("yyyy-MM-dd");
			if (reader.readLine() == null) // 跳过标题行
				return;
			while ((line = reader.readLine()) != null)
			{
				lineNumber++;

				if (lineNumber % 100 == 0)
					System.out.println("Processing line " + lineNumber + " ......");

				String[] parts = line.split(",");
				String date = parts[0];
				String visitor = parts[2];
				String home = parts[3];
				String OPENTOT = parts[4];
				int scoreSum = Integer.parseInt(parts[12]);

				try
				{
					NbaScorePredictor scorePredictor = new NbaScorePredictor(connection);
					PlayerPairScoreGain[] scoreGains = scorePredictor.getPlayerPairScoreGains(home, visitor, date);
					double predictedSum = scorePredictor.getPridictedTotalScore(scoreGains, date);

					if (Double.compare(predictedSum, Double.NaN) == 0)
					{
						System.out.printf("Not enough history data. \nLine %1d: %2s\n", lineNumber, line);
						// return;
					}
					else
						writer.write(date + ", " + visitor + ", " + home + ", " + OPENTOT + ", " + scoreSum + ", " + predictedSum + "\n");
				}
				catch (Exception ex)
				{
					System.out.println(ex.getMessage());
					System.out.printf("Line %1d: %2s\n", lineNumber, line);
				}
				if (lineNumber == 2000)
					return;
			}
		}
		catch (IOException e)
		{
			System.err.println("Unable to read file. " + e.getMessage());
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		// catch (ParseException e)
		// {
		// System.err.printf("Line: %1d\t Wrong date format. \n%2s", lineNumber, line);
		// }
		finally
		{
			if (reader != null)
			{
				//@formatter:off
				try{reader.close();}
				catch (IOException e1){}
				//@formatter:on
			}

			if (writer != null)
			{
				//@formatter:off
				try{writer.close();}
				catch (IOException e1){}
				//@formatter:on
			}

			//@formatter:off
			try	{connection.close();}
			catch(Exception e){}
			//@formatter:on
		}

	}

}
